package org.ccay.manage.hypertext.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Named;

import org.ccay.core.exception.ApplicationException;
import org.ccay.core.io.VFSFileObject;
import org.ccay.core.log.CcayLoggerFactory;
import org.ccay.core.log.ILogger;
import org.ccay.core.util.StringUtil;
import org.ccay.security.util.SecurityUtil;
import org.ccay.upload.FolderSplitType;
import org.ccay.upload.IUploadFileConsumer;
import org.ccay.upload.UploadSettingVO;

/**
 * 用于图片上传的处理
 * 
 */
@Named("IUploadFileConsumer.hyperTextImage")
public class ImageUploadConsumer implements IUploadFileConsumer {
	
	/**
	 * 日志组件
	 */
	private static final ILogger logger = CcayLoggerFactory.getLogger(ImageUploadConsumer.class);
	

	@Override
	public boolean validatePrivilege(Map<String, String> paramMap) {
		return SecurityUtil.checkPermissionNoThrowsException("hypertextManagement:create");
	}

	/**
	 * 最大允许的文件个数
	 */
	private static final int MAX_FILE_COUNT = 1;

	/**
	 * 最大允许的文件大小
	 */
	private static final long MAX_SIZE = 1024 * 1024 * 2;

	/**
	 * 最大使用的内存
	 */
	private static final int MAX_MEMORY = 1024 * 1024 * 2;

	@Override
	public UploadSettingVO getUploadSetting(Map<String, String> paramMap) {
		
		UploadSettingVO setting = new UploadSettingVO();

		setting.setFileSplitType(FolderSplitType.ByDay);
		setting.setFileTypesAllowed(Arrays.asList(new String[] { "jpg", "jpeg", "png", "gif" }));
		setting.setMaxFileCount(MAX_FILE_COUNT);
		setting.setMaxFileSize(MAX_SIZE);
		setting.setMaxMemory(MAX_MEMORY);
		setting.setVfsModule("hyperTextImage");
		return setting;
	}

	@Override
	public Object processFiles(Map<String, String> parameters, List<VFSFileObject> fileInfos)
			throws ApplicationException {
		List<String> urls = new ArrayList<String>();
		for(VFSFileObject file :fileInfos){
			//将图片归档
			VFSFileObject archivedFile = file.copyToArchive();
			urls.add("servlet/download?dlType=hyperTextImage&path="+archivedFile.getRelativePath());
			logger.debug("To delete VFS fileObject : {0}", file.getURI());
			file.delete();
			file.close();
		}
		
		Map<String,Object> obj = new HashMap<String,Object>();
		obj.put("error", 0);
		obj.put("url", StringUtil.join(urls, ","));
		return obj;
	}
}
